<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container">
      <!-- 搜索 -->
      <div class="searchbox">
        <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select">
          <template #append>
            <el-button @click="search">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="adduserVisible = true">添加用户</el-button>
        <!-- 添加用户对话框 -->
        <el-dialog v-model="adduserVisible" title="添加用户">
          <el-form
            :model="adduserFrom"
            :label-width="70"
            class="demo-ruleForm"
            :rules="addrules"
            ref="adduserFromref"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="adduserFrom.username" type="text" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="adduserFrom.password" type="password" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="adduserFrom.email" type="text" />
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="adduserFrom.mobile" type="text" />
            </el-form-item>
            <el-form-item>
              <el-button @click="adduserVisible = false">取消</el-button>
              <el-button type="primary" @click="adduserOK(adduserFromref)">确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 表格主体 -->
      <el-table :data="userlist" style="width: 100%" border stripe size="large">
        <el-table-column prop="num" label="#" width="50" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="joker" label="角色" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="statuschange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" circle @click="edit(scope.row)">
              <el-icon>
                <EditPen />
              </el-icon>
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" circle @click="deleteThere(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
            <el-button type="warning" circle @click="distributionThere(scope.row)">
              <el-icon>
                <Setting />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->

      <div class="pagination">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="queryInfo.pagenum"
            v-model:page-size="queryInfo.pagesize"
            :page-sizes="[2, 5, 10, 15]"
            layout="total,sizes, prev, pager, next, jumper"
            :total="totals"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>
      <!-- 编辑对话框 -->
      <el-dialog v-model="editVisible" title="修改用户信息">
        <el-form
          :model="editFrom"
          :label-width="70"
          class="demo-ruleForm"
          :rules="addrules"
          ref="editFromref"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editFrom.username" type="text" disabled />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email" type="text" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editFrom.mobile" type="text" />
          </el-form-item>
          <el-form-item >
            <el-button @click="editVisible = false">取消</el-button>
            <el-button type="primary" @click="editThere(editFromref)">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog v-model="distributionVisible" title="分配角色">
        <el-form
          :model="distributionFrom"
          :label-width="100"
          class="demo-ruleForm"
          :rules="addrules"
        >
          <el-form-item label="当前用户">{{distributionFrom.username}}</el-form-item>
          <el-form-item label="当前角色">{{distributionFrom.joker}}</el-form-item>
          <el-form-item label="分配角色">
            <el-select
              v-model="distributionFrom.newjoker"
              class="m-2"
              placeholder="请选择角色"
              size="large"
            >
              <el-option
                v-for="item in userRolelist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="distributionVisible = false">取消</el-button>
            <el-button type="primary" @click="distributionThereOK">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { reactive, ref, onBeforeMount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUsers,
  postAddUser,
  putUserStatus,
  deleteUser,
  putUserRole,
  getUserRoles,
  puteditUser
} from "../tools/ajax.js";
const route = useRoute();
const router = useRouter();

const userRolelist = reactive([]);
const adduserFromref = reactive({});
const editFromref = reactive({});
const userlist = reactive([]);
const adduserVisible = ref(false);
const editVisible = ref(false);
const distributionVisible = ref(false);
const adduserFrom = reactive({
  username: "",
  password: "",
  email: "",
  mobile: ""
});
const distributionFrom = reactive({
  username: "",
  joker: "",
  newjoker: "",
  id: ""
});
const editFrom = reactive({
  username: "",
  email: "",
  mobile: "",
  id: ""
});
const queryInfo = reactive({
  query: "",
  // 当前页数
  pagenum: 1,
  // 每页显示多少数据
  pagesize: 5
});
const totals = ref(0);

const addrules = {
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: "change"
    },
    {
      min: 2,
      max: 6,
      message: "账号长度在2-6位之间",
      trigger: "change"
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change"
    },
    {
      min: 4,
      max: 12,
      message: "密码长度在4-12位之间",
      trigger: "change"
    }
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "change"
    }
  ],
  mobile: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change"
    }
  ]
};
function getlist() {
  getUsers({ params: queryInfo }).then(res => {
    console.log(res.data);
    totals.value = res.data.total;
    userlist.splice(0, 1000);
    res.data.users.forEach((item, index) => {
      userlist.push({
        num: index + 1,
        name: item.username,
        email: item.email,
        phone: item.mobile,
        joker: item.role_name,
        status: item.mg_state,
        operation: item.id
      });
    });
  });
}
// 修改用户状态
function statuschange(item) {
  console.log(item.status, item.operation);
  putUserStatus({
    id: item.operation,
    status: item.status
  }).then(res => {
    console.log(res);
    if (res.meta.status == 200) {
      ElMessage.success(res.meta.msg);
    } else {
      ElMessage.error(res.meta.msg);
    }
  });
}
function handleSizeChange() {
  console.log("每页条数改变了");
  getlist();
}
function handleCurrentChange() {
  console.log("页面改变了");
  getlist();
}
function search() {
  console.log("搜索执行了");
  getlist();
}

// 添加用户
function adduserOK(from) {
  from.validate(flag => {
    if (flag) {
      console.log(adduserFrom);
      postAddUser(adduserFrom).then(res => {
        console.log(res);
        if (res.meta.status == 201) {
          ElMessage.success(res.meta.msg);
          getlist();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
      adduserVisible.value = false;
    } else {
      return;
    }
  });
}

// 编辑信息
function editThere(from) {
  from.validate(flag => {
    if (flag) {
      console.log(editFrom);
      puteditUser({
        id: editFrom.id,
        email: editFrom.email,
        mobile: editFrom.mobile
      }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          ElMessage.success(res.meta.msg);
          editVisible.value = false;
          getlist();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    } else {
      return;
    }
  });
}
function edit(item) {
  console.log(item);
  editVisible.value = true;
  editFrom.username = item.name;
  editFrom.email = item.email;
  editFrom.mobile = item.phone;
  editFrom.id = item.operation;
}

// 删除用户
function deleteThere(item) {
  ElMessageBox.confirm("此操作将永久删除该用户,是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteUser({ id: item.operation }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          getlist();
          ElMessage.success(res.meta.msg);
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    })
    .catch(() => {
      ElMessage.warning("取消删除");
    });
}

// 分配
function distributionThere(item) {
  console.log(item);
  distributionVisible.value = true;
  distributionFrom.username = item.name;
  distributionFrom.joker = item.joker;
  distributionFrom.id = item.operation;
  distributionFrom.newjoker = "";
}
function distributionThereOK() {
  console.log(distributionFrom);
  if (distributionFrom.newjoker) {
    putUserRole({
      id: distributionFrom.id,
      rid: distributionFrom.newjoker
    }).then(res => {
      console.log(res);
      if (res.meta.status == 200) {
        ElMessage.success(res.meta.msg);
        distributionVisible.value = false;
        getlist();
      } else {
        ElMessage.error(res.meta.msg);
      }
    });
  } else {
    ElMessage.error("请选择需要分配的角色");
  }
}
onBeforeMount(() => {
  getlist();
  getUserRoles().then(res => {
    console.log(res.data);
    res.data.forEach((item, i) => {
      userRolelist.push({
        name: item.roleName,
        id: item.id
      });
    });
  });
});
</script>

<style scoped>
.searchbox {
  margin-bottom: 20px;
  display: flex;
}
.pagination {
  margin-top: 20px;
}
.input-with-select {
  width: 400px;
  height: 40px;
}
.searchbox > .el-button.el-button--primary {
  height: 40px;
  margin-left: 30px;
}
</style>